package com.clound.product.service.Impl;

import com.clound.product.common.ProductInfoOutput;
import com.clound.product.common.utils.JsonUtil;
import com.clound.product.dao.ProductDao;
import com.clound.product.dataObject.ProductInfo;
import com.clound.product.dto.CartDTO;
import com.clound.product.enums.ProductStatusEnum;
import com.clound.product.enums.ResultEnum;
import com.clound.product.exception.ProductException;
import com.clound.product.service.ProductService;
import com.google.common.collect.Lists;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * Created by zzy on 2018/4/7.
 */
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductDao productDao;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Override
    public List<ProductInfo> findUpAll() {
        Integer status=ProductStatusEnum.UP.getCode();
        return productDao.findByProductStatus(status);
    }

    @Override
    public List<ProductInfo> findByProductIdIn(List<String> productIdList) {
        return productDao.findByProductIdIn(productIdList);
    }

    @Override
    public void decreaseStock(List<CartDTO> cartDTOList) {
        List<ProductInfo> productInfoList=  decreaseStockProcess(cartDTOList);
        List<ProductInfoOutput> sendList=Lists.newArrayList();
        for (ProductInfo productInfo:productInfoList){
            ProductInfoOutput productInfoOutput=new ProductInfoOutput();
            BeanUtils.copyProperties(productInfo,productInfoOutput);
            sendList.add(productInfoOutput);
            //发送MQ消息
        }
        amqpTemplate.convertAndSend("productInfo", JsonUtil.Object2Json(sendList));

    }

    @Transactional
    public List<ProductInfo> decreaseStockProcess(List<CartDTO> cartDTOList) {
        List<ProductInfo> productInfoList= Lists.newArrayList();
        for (CartDTO cartDTO:cartDTOList){
            Optional<ProductInfo> productInfoOptional =  productDao.findById(cartDTO.getProductId());
            //商品是否存在
            if(!productInfoOptional.isPresent()){
                throw new ProductException(ResultEnum.PRODUCT_NOT_EXIST);
            }
            ProductInfo productInfo=productInfoOptional.get();
            //库存是否足够
            Integer result= productInfo.getProductStock()-cartDTO.getProductQuantity();
            if(result<0){
                throw new ProductException(ResultEnum.PRODUCT_STOCK_ERROR);
            }
            productInfo.setProductStock(result);
            productDao.save(productInfo);
            productInfoList.add(productInfo);
        }
        return productInfoList;
    }
}
